
import plugins from '../plugins';

function saveSlotPage(context) {
	return context.fetchHtmlScript('monitor/tag_2019_save_slot.html').then(html => {
		return createSaveSlotPage(context, html);
	});
}

function createSaveSlotPage(context, html) {
	return {
		template : html,
		data : function () {
			return {
				status : null,
				currentSlot : null, // 当前存在哪个存档, 一般没有就是 null
				saveAsSlot : '',

				/** @type {{name:string, id:string}[]} */ archives : [],
				/** @type {{name:string, id:string}[]} */ curArchives : [],

				// 为防止刷新次数过多
				refreshHandler : 0,
				lastRefreshTime : 0,

				// 右边那栏显示存档详情 / 当前屏幕详情
				viewCurrent : true, // 如果显示屏幕详情, 为 true, 否则为 false
				viewSaveName : null,
				viewArchive : null,
				viewLoading : false,
			}
		},
		props : {
			sid : String,
		},
		methods : {
			onScreenUpdated : function() {
				let status = context.getStatus(this.sid);
				if (status == null || status.data == null) {
					return;
				}
				status = JSON.parse(JSON.stringify(status));
				for (var key in status.data.tags) {
					let tag = status.data.tags[key];
					tag.type = tag.series + "/" + tag.pendant;
				}

				this.currentSlot = status.data.slot || null;
				this.status = status;
				this.refreshArchives(true);
			},
			refreshArchives : function(force = false) {
				let now = Date.now();
				if (!force && now - this.lastRefreshTime < 60000) {
					return;
				}

				this.lastRefreshTime = now;
				listAllSlot().then(slots => {
					this.archives = slots;
					this.curArchives = slots.filter(s => this.currentSlot === s.slotName);
				});
			},

			// 另存为
			btnSaveAs : function() {
				const slot = this.saveAsSlot;
				if (slot === '') {
					this.$message.error('存档名不能为空');
				}
				createSave(slot).then(id => this.btnSave(id, slot));
			},
			btnSave : function(id, saveName) {
				const data = this.extractSave();
				writeSave(id, data)
					.then(() => {
						this.$message.success(`保存存档 "${saveName}" 成功`);
						context.sendCommand(this.sid, 'setSaveSlot', {
							slot : saveName,
							reload : false
						});
					});
			},
			btnRead : function(id, saveName) {
				readSave(id) // 先读取就是看看存档数据在不在, 有空存档的可能性的
					.then(() => {
						context.sendCommand(this.sid, 'setSaveSlot', {
							slot : saveName,
							reload : true
						});
					})
					.catch(e => {
						console.error(`读取存档 ${saveName} 失败`, e);
						this.$message.error(`读取存档 ${saveName} 失败`);
					})
			},
			btnView : function(id, saveName) {
				this.viewCurrent = false;
				this.viewLoading = true;
				this.viewSaveName = saveName;
				readSave(id)
					.then(data => {
						this.viewLoading = false;
						data.plugins.forEach(p => p.type = `${p.series}/${p.pendant}`);
						this.viewArchive = data;
					});
			},

			extractSave : function() {
				const data = this.status.data;
				/** @type {number[]} */ const order = data.order;
				const d = {};
				d.version = data.version;
				d.plugins = order.map(id => {
					let tag = data.tags[id];
					let plugin = {};
					plugin.data = tag.data;
					plugin.series = tag.series;
					plugin.pendant = tag.pendant;
					return plugin;
				});
				return d;
			},

			// 右边相关
			btnViewCurrent : function() {
				this.viewCurrent = true;
				this.viewArchive = null;
				this.viewLoading = false;
			},

			tagName : function (id) {
				return plugins.pluginType(this.status.data.tags[id]);
			},
			pluginName : function (id) {
				return plugins.pluginTitle(this.status.data.tags[id]);
			},
			pluginColor : function (id) {
				return plugins.pluginTagColor(this.status.data.tags[id]);
			},
			tagNameForSave : function (plugin) {
				return plugins.pluginType(plugin);
			},
			pluginNameForSave : function (plugin) {
				return plugins.pluginTitle(plugin);
			},
			pluginColorForSave : function (plugin) {
				return plugins.pluginTagColor(plugin);
			},

			tickRefresh : function() {
				this.refreshHandler = requestAnimationFrame(this.tickRefresh.bind(this));
				this.refreshArchives();
			}
		},
		mounted : function() {
			this.onScreenUpdated(); // 更新 status
			this.refreshHandler = requestAnimationFrame(this.tickRefresh.bind(this));
			context.getBus().$on(context.events.KEY_SCREEN_REFRESH, this.onScreenUpdated);
			context.getBus().$on(context.events.KEY_SCREEN_CREATED, this.onScreenUpdated);
			context.getBus().$on(context.events.KEY_SCREEN_UPDATED, this.onScreenUpdated);
		},
		destroyed : function() {
			cancelAnimationFrame(this.refreshHandler);
			context.getBus().$off(context.events.KEY_SCREEN_REFRESH, this.onScreenUpdated);
			context.getBus().$off(context.events.KEY_SCREEN_CREATED, this.onScreenUpdated);
			context.getBus().$off(context.events.KEY_SCREEN_UPDATED, this.onScreenUpdated);
		}
	};
}

/* **********
 * 存档获取 *
 ********** */

/**
 * 罗列所有的存档
 * @returns {Promise<{name:string, id:string, slotName:string}[]>}
 */
function listAllSlot() {
	return fetch('/aurora/asset/save/list/name_tag')
		.then(d => d.json())
		.then(d => {
			if (!d.result) {
				throw { msg: '查询存档失败', data: d };
			}
			const array = d.data.filter(item => item.name.startsWith("tag_2019::"));
			return array.map(item => { return {
				name: item.name,
				id: item.id,
				slotName: item.name.substring("tag_2019::".length),
			};});
		});
}

/**
 * 罗列所有的存档
 * @param {string} id
 * @returns {Promise<{version:string,plugins:{data:any,series:string,pendant:string}[]}>}
 */
function readSave(id) {
	return fetch(`/aurora/asset/save/read/${id}`)
		.then(d => d.json());
}

/**
 * 创建存档
 * @param {string} name
 * @returns {Promise<string>}
 */
function createSave(name) {
	return fetch(`/aurora/asset/save/create?series=name_tag&name=tag_2019::${encodeURIComponent(name)}`)
		.then(d => d.json())
		.then(d => d.data.id);
}

/**
 * 写入存档
 * @param {string} id
 * @param {any} archive
 * @returns {Promise<string>}
 */
function writeSave(id, archive) {
	return fetch(`/aurora/asset/save/write/${id}`, { method: 'put', body: JSON.stringify(archive) })
		.then(d => d.json())
		.then(d => d.data.id);
}

export default saveSlotPage;
